<?php

namespace App\Jobs;

use App\Libs\Company\SheetTemplateHandler\Manager;
use App\Models\AggregateReport;
use App\Models\SheetTemplate;
use App\Models\Task;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class GenerateAggregate implements ShouldQueue, ShouldBeUnique
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public SheetTemplate $sheetTemplate;

    public Task $task;

    /**
     * The number of seconds after which the job's unique lock will be released.
     *
     * @var int
     */
    public $uniqueFor = 3600;

    /**
     * Get the unique ID for the job.
     */
    public function uniqueId(): string
    {
        return $this->sheetTemplate->id;
    }

    /**
     * Create a new job instance.
     */
    public function __construct(SheetTemplate $sheetTemplate, Task $task)
    {
        $this->sheetTemplate = $sheetTemplate;
        $this->task = $task;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $manager = Manager::createAggregateHandler($this->sheetTemplate, $this->task);
        $output = $manager->generateAbstract();
        $aggregateReport = AggregateReport::firstOrNew([
            'sheet_template_id' => $this->sheetTemplate->id,
            'frequency' => $this->task->frequency,
            'year' => $this->task->year,
            'key' => $this->task->key,
        ]);
        $aggregateReport->data = $output;
        $aggregateReport->save();
        $aggregateReport->sheetTemplate
            ->aggregateTemplates()
            ->wherePivot('frequency', $this->task->frequency)
            ->get()
            ->each(function ($template) {
                self::dispatch($template, $this->task);
            });
    }
}
